from typing import List

from PyQt5.QtCore import QPropertyAnimation
from PyQt5.QtWidgets import QStackedWidget, QWidget, QGraphicsOpacityEffect


class OpacityAniStackedWidget(QStackedWidget):
    """具有淡入淡出动画的堆叠小部件,用于在切换页面时添加淡入淡出动画"""

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.__next_index = 0
        self.__effects = []  # type:List[QPropertyAnimation | QGraphicsOpacityEffect]
        self.__antis = []  # type:List[QPropertyAnimation]

    def add_widget(self, widget: QWidget):
        """
        添加小部件
        :param widget:
        :return:
        """
        super().addWidget(widget)

        effect = QGraphicsOpacityEffect(widget)
        effect.setOpacity(1)
        ani = QPropertyAnimation(effect, b"opacity", self)
        ani.setDuration(220)
        ani.finished.connect(lambda: self.__on_finished)
        self.__effects.append(effect)
        self.__antis.append(ani)
        widget.setGraphicsEffect(effect)

    def setCurrentIndex(self, index: int):
        """
        设置当前小部件
        :param index:
        :return:
        """
        __index = self.currentIndex()
        if __index == index:
            return

        if index > __index:
            ani = self.__antis[__index]
            ani.setStartValue(0)
            ani.setEndValue(1)
            super().setCurrentIndex(index)
        else:
            ani = self.__antis[index]
            ani.setStartValue(1)
            ani.setEndValue(0)

        self.widget(index).show()
        self.__next_index = index
        ani.start()

    def __on_finished(self):
        """
        动画结束时
        :return:
        """
        super().setCurrentIndex(self.__next_index)
